package org.orbis.communicate.filter;

import java.util.Arrays;
import java.util.BitSet;
import org.orbis.communicate.FlagsResult;
import org.orbis.constants.Constants;

public class FieldFilter implements Filter<FlagsResult[], boolean[]>{
	@Override
	public FlagsResult[] intersection(boolean[] filter, FlagsResult[]... part){
		return null;
	}

	@Override
	public FlagsResult[] join(boolean[] filter, FlagsResult[]... part){
		if(part == null) return null;
		FlagsResult[] results = new FlagsResult[part.length * Constants.PERUSER];

		int parts = part.length;
		int[] currentIndex = new int[parts];
		BitSet reachEnd = new BitSet(parts);
		for(int i = 0; i < parts; i++){
			if(!filter[i]) reachEnd.set(i);
			if(part[i] == null) reachEnd.set(i);
			else if(part[i].length == 0) reachEnd.set(i);
			currentIndex[i] = 0;
		}

		// Stop if all parts get end point
		int count = 0;
		while(reachEnd.cardinality() < parts){
			// Find 'first' ID
			long minimum = Long.MAX_VALUE;
			int index = -1;
			for(int i = 0; i < parts; i++){
				if(reachEnd.get(i)) continue;
				if(minimum > part[i][currentIndex[i]].ID()){
					minimum = part[i][currentIndex[i]].ID();
					index = i;
				}
			}

			results[count++] = part[index][currentIndex[index]];

			for(int i = 0; i < parts; i++){
				if(reachEnd.get(i)) continue;
				if(minimum == part[i][currentIndex[i]].ID()) currentIndex[i]++;
				if(currentIndex[i] >= part[i].length) reachEnd.set(i);
			}
		}

		FlagsResult[] resultArray = Arrays.copyOf(results, count);

		return resultArray;
	}

	@Override
	public FlagsResult[] filter(boolean[] filter, FlagsResult[] list){
		return null;
	}
}
